昨天產生出推播了,今天來刪除特定推播吧。
在產生推播的時候,有設定他的ID,這裡是將他的ID跟Realm的資料ID綁在一起,這樣就能同時刪除資料和推播。
    @objc func deleteAlarm() {
        let realm = try! Realm()
        let cells = realm.objects(AlarmRealm.self)
        let deleteCell = cells[addPageValue.pageValue.selectCell]
    
        try! realm.write{
            realm.delete(deleteCell)
        }
        
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [cells[addPageValue.pageValue.selectCell].ID])
        
        self.navigationController?.popViewController(animated: true)
    }
偶爾只是需要將鬧鐘關閉,而不是刪除,所以需要在Cell裡寫些功能,讓鬧鐘可以自由開關。
    @IBAction func onOff(_ sender: Any) {
        let realm = try! Realm()
        let cells = realm.objects(AlarmRealm.self)
        try! realm.write {
            cells[tag].switchOnOff = !cells[tag].switchOnOff
        }
        let repeatDays = [cells[tag].Sunday,
                          cells[tag].Monday,
                          cells[tag].Tuesday,
                          cells[tag].Wednesday,
                          cells[tag].Thursday,
                          cells[tag].Friday,
                          cells[tag].Saturday]
        var repeatDayCount = 0
        
        let alarmVC = AlarmViewController()
        
        if onOffSwitch.isOn {
            alarmVC.createNotificationId(selectRow: tag)
            for i in 1...7 {
                if repeatDays[i-1] {
                    alarmVC.createNotification1(selectRow: tag, repeatDay: i)
                    repeatDayCount += 1
                }
            }
            if repeatDayCount == 0 {
                alarmVC.createNotification2(selectRow: tag)
            }
        } else {
            UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [cells[tag].ID])
        }
    }
到這裡,整個鬧鐘結束了,明天來處理畫面。